<?php

/**
 * 聚合新闻头条列表发起请求-PHP代码
 * 功能：最新新闻头条，各类社会、国内、国际、体育、娱乐、科技等资讯。
 */

// 请求的接口URL
$apiUrl = 'http://v.juhe.cn/toutiao/index';

// 请求参数
$params = [
    'type' => 'top', // 新闻类型
    'key' => '21338cfdb37d9c34fa492d25bef2d117', // 接口调用key，通过聚合平台申请开通
];

$paramsString = http_build_query($params);

// 发起接口请求
$response = juheHttpRequest($apiUrl, $paramsString, 1);

// 处理接口返回结果，根据自身业务逻辑修改处理
$paramstring = http_build_query($params);
$content = juheHttpRequest($apiUrl, $paramstring, 1);
$result = json_decode($content, true);

if ($result) {

    if ($result['error_code'] == 0) {
        echo json_encode(['code' => 1, 'msg' => 'Ok', 'data' => $result['result']['data']]);
    } else {
        echo json_encode(['code' => 2, 'msg' => $result['reason'], 'data' => []]);
    }

} else {
    echo json_encode(['code' => 2, 'msg' => '请求失败', 'data' => []]);
}

/**
 * 发起网络请求函数
 * @param string $url 请求的URL
 * @param bool $params 请求的参数内容
 * @param int $ispost 是否POST请求
 * @return bool|string 返回内容
 */
function juheHttpRequest($url, $params = false, $ispost = 0)
{
    $httpInfo = [];
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'JUHE API');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
    curl_setopt($ch, CURLOPT_TIMEOUT, 12);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if ($ispost) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        if ($params) {
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }
    $response = curl_exec($ch);
    if ($response === FALSE) {
        // echo "cURL Error: ".curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    return $response;
}
